package com.longteng.testng;

import com.beust.jcommander.internal.Maps;
import jodd.bean.BeanUtil;
import jodd.util.StringTemplateParser;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * Created by sky on 15-12-25
 */
public class DefaultValueTransfer implements ValueTransfer{


    private Map<String,Object> beans = Maps.newHashMap();

    private Map<String,MethodInvoker> invokerMap = Maps.newHashMap();

    private Map<String,String> params = Maps.newHashMap();


    @Override
    public String transfer(String value) {
        StringTemplateParser templateParser = new StringTemplateParser();
        return templateParser.parse(value, macroName -> {
            if(macroName.endsWith("()")){
                MethodInvoker methodInvoker = invokerMap.get(StringUtils.substringBefore(macroName,"()"));
                if(methodInvoker==null){
                    throw new RuntimeException("未定义该方法:"+ macroName);
                }else{
                    return methodInvoker.invoke();
                }
            }else{
                if(beans.containsKey(macroName)&& macroName.contains(".")){
                    Object bean = beans.get(StringUtils.substringBefore(macroName,"."));
                    return String.valueOf(BeanUtil.getPropertySilently(bean, StringUtils.substringAfter(macroName,".")));
                }else{
                    return params.get(value);
                }
            }
        });
    }


    public void addBean(String name,Object object){
        this.beans.put(name,object);
    }

    public void addParam(String name,String value){
        this.params.put(name,value);
    }

    public void addMethod(String name,MethodInvoker invoker){
        this.invokerMap.put(name,invoker);
    }
}
